﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.DBHelp;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Models;

namespace UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Method
{
    public class AddVoucherAssem
    {
        public static string DBname = ConfigurationManager.AppSettings["U8DBNAME"].ToString();
        public static string Insert(string filename, string jsons)
        {
            Result mr = new Result();
            List<ItemsItemR> lim = new List<ItemsItemR>();
            int row = 0;
            string res = "";
            bool flag = !string.IsNullOrEmpty(jsons);
            if (flag)
            {
                try
                {
                    int irow = 0;//转换单子表行号
                    List<string> list = new List<string>();
                    RD10 rd = JsonConvert.DeserializeObject<RD10>(jsons);
                    string dCode = rd.dCode;
                    if (string.IsNullOrEmpty(dCode))
                    {
                        row = 1;
                        res += "外部系统单号不允许为空!检查dCode字段";
                    }
                    else
                    {
                        int ifex2 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
                        {
                            "select COUNT(*) from ",
                            AddRD01.DBname,
                            "..assemvouch where cAVCode='",
                            dCode,
                            "'"
                        })));
                        if (ifex2 > 0)
                        {
                            row = 1;
                            res = string.Concat(new string[]
                            {
                                res,
                                "外部系统单号[",
                                dCode,
                                "]在U8系统已存在",
                                filename,
                                "信息!"
                            });
                        }
                    }
                    string dDate = rd.dDate;
                    if (!string.IsNullOrEmpty(dDate))
                    {
                        if (!PublicMet.IsDate(dDate))
                        {
                            row = 1;
                            res += "日期格式不正确!例：[2024-11-12]";
                        }
                    }
                    else
                    {
                        row = 1;
                        res += "日期不允许为空！检查dDate字段";
                    }
                    string Period = Convert.ToDateTime(rd.dDate).Year.ToString() + Convert.ToDateTime(rd.dDate).Month.ToString().PadLeft(2, '0');
                    string jsql = " select bflag_ST from " + DBname + "..GL_mend where iYPeriod = '" + Period + "' ";
                    string bflag_ST = DBHelp.SQLHelper.GetString(jsql);
                    if (bflag_ST == "True")
                    {
                        row = 1;
                        res += "日期[" + rd.dDate + "]库存已关账！";
                    }
                    string cMaker = rd.cMaker;
                    bool flag12 = string.IsNullOrEmpty(cMaker);
                    if (flag12)
                    {
                        row = 1;
                        res += "制单人不允许为空!检查cMaker字段";
                    }
                    else
                    {
                        string cMakers = PublicMet.CUSERNAME(cMaker);
                        if (string.IsNullOrEmpty(cMakers))
                        {
                            row = 1;
                            res += "未找到编码为[" + cMaker + "]的制单人员!";
                        }
                        else
                        {
                            cMaker = cMakers;
                        }
                    }
                    string cHandler = rd.cHandler;
                    bool flag13 = string.IsNullOrEmpty(cHandler);
                    if (flag13)
                    {
                        row = 1;
                        res += "审核人不允许为空!检查cHandler字段";
                    }
                    else
                    {
                        string cHandlers = PublicMet.CUSERNAME(cHandler);
                        if (string.IsNullOrEmpty(cHandlers))
                        {
                            row = 1;
                            res += "未找到编码为[" + cHandler + "]的审核人员!";
                        }
                        else
                        {
                            cHandler = cHandlers;
                        }
                    }
                    string cordcode = rd.cordcode;
                    if (string.IsNullOrEmpty(cordcode))
                    {
                        row = 1;
                        res += "出库类型不允许为空!检查cordcode字段";
                    }
                    else
                    {
                        int ifex3 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
                        {
                            "select COUNT(*) from ",
                            AddRD01.DBname,
                            "..Rd_Style where cRdCode='",
                            cordcode,
                            "'"
                        })));
                        bool flag10 = ifex3 == 0;
                        if (flag10)
                        {
                            row = 1;
                            res = res + "出库类型[" + cordcode + "]在U8系统不存在!";
                        }
                    }
                    string cirdcode = rd.cirdcode;
                    if (string.IsNullOrEmpty(cirdcode))
                    {
                        row = 1;
                        res += "入库类型不允许为空!检查cirdcode字段";
                    }
                    else
                    {
                        int ifex3 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
                        {
                            "select COUNT(*) from ",
                            AddRD01.DBname,
                            "..Rd_Style where cRdCode='",
                            cirdcode,
                            "'"
                        })));
                        bool flag10 = ifex3 == 0;
                        if (flag10)
                        {
                            row = 1;
                            res = res + "入库类型[" + cirdcode + "]在U8系统不存在!";
                        }
                    }
                    string cMemo = rd.cMemo;
                    string cAcc_Id = AddRD01.DBname.Substring(7, 3);

                    int fidas = 0;
                    int cidas = 0;
                    string sql = " select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_Id + "' and cVouchType='as' ";
                    DataTable dtidas = SQLHelper.GetDataTable(sql);
                    bool flag17 = dtidas.Rows.Count > 0;
                    if (flag17)
                    {
                        fidas = Convert.ToInt32(dtidas.Rows[0]["iFatherId"].ToString());
                        cidas = Convert.ToInt32(dtidas.Rows[0]["iChildId"].ToString());
                    }
                    else
                    {
                        sql = " insert into UFSystem..UA_Identity (cAcc_Id,cVouchType,iFatherId,iChildId)  values('" + cAcc_Id + "','as',0,0) ";
                        SQLHelper.ExecuteSql(sql);
                    }
                    fidas++;
                    list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='as' ");
                    string ASID = "1" + string.Format("{0:D9}", fidas);
                    string ASCode = dCode;
                    string csysbarcodeas = "||st15|" + ASCode;
                    int cTransFlag = 1;
                    sql = "insert into " + DBname + "..assemvouch (cAVCode,cVouchType,dAVDate,cMaker,iNetLock,ID,bTransFlag,VT_ID," +
                    "cVerifyPerson,dVerifyDate,parentscrp,dnmaketime,dnverifytime,iPrintCount,ctransflag,iswfcontrolled,csysbarcode,cavmemo,cirdcode,cordcode) values" +
                    "('" + ASCode + "','15','" + dDate + "','" + cMaker + "','0','" + ASID + "','0','91','" + cHandler + "','" + dDate + "" +
                    "','0.0000',getdate(),getdate(),0,'" + cTransFlag.ToString() + "','0','" + csysbarcodeas + "','" + cMemo + "','"+cirdcode+"','"+cordcode+"')";
                    list.Add(sql);

                    int cou = rd.Items.Count;
                    int before = 0, after = 0;
                    for (int i = 0; i < cou; i++)
                    {
                        ItemsItemR mir = new ItemsItemR();
                        string bAVType = rd.Items[i].bAVType;
                        if (string.IsNullOrEmpty(bAVType))
                        {
                            row = 1;
                            res += "明细行转换类型[bAVType]未传递！";
                        }
                        if (bAVType.Equals("转换前"))
                        {
                            before++;
                        }
                        else if (bAVType.Equals("转换后"))
                        {
                            after++;
                        }
                        else
                        {
                            row = 1;
                            res += "对应的转换类型(转换前or转换后)[bAVType]为空或传递了错误的值！";
                        }
                        string RowNo = rd.Items[i].RowNo;
                        if (string.IsNullOrEmpty(RowNo))
                        {
                            row = 1;
                            res = res + "第[" + (i + 1).ToString() + "]行行号不允许为空!检查RowNo字段";
                        }
                        string cInvCode = rd.Items[i].cInvCode;
                        if (string.IsNullOrEmpty(cInvCode))
                        {
                            row = 1;
                            res = res + "第[" + (i + 1).ToString() + "]行存货编码不允许为空!检查cInvCode字段";
                        }
                        else
                        {
                            int ifex7 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
                            {
                                "select COUNT(*) from ",
                                AddRD01.DBname,
                                "..Inventory where cinvcode='",
                                cInvCode,
                                "'"
                            })));
                            bool flag22 = ifex7 == 0;
                            if (flag22)
                            {
                                row = 1;
                                res = string.Concat(new string[]
                                {
                                    res,
                                    "第[",
                                    (i + 1).ToString(),
                                    "]行存货编码[",
                                    cInvCode,
                                    "]在U8系统不存在!"
                                });
                            }
                        }
                        string iQuantity = rd.Items[i].iQuantity;
                        bool flag23 = string.IsNullOrEmpty(iQuantity);
                        if (flag23)
                        {
                            row = 1;
                            res = res + "第[" + (i + 1).ToString() + "]行数量不允许为空!检查iQuantity字段!";
                        }
                        else
                        {
                            bool flag24 = !PublicMet.IsNumberic(iQuantity);
                            if (flag24)
                            {
                                row = 1;
                                res = string.Concat(new string[]
                                {
                                    res,
                                    "第[",
                                    (i + 1).ToString(),
                                    "]行数量[",
                                    iQuantity,
                                    "]非数字类型!"
                                });
                            }
                        }
                        string cBatch = rd.Items[i].cBatch;
                        bool cba = Convert.ToBoolean(SQLHelper.GetString(string.Concat(new string[]
                        {
                            "select bInvBatch from ",
                            AddRD01.DBname,
                            "..Inventory where cinvcode='",
                            cInvCode,
                            "'"
                        })));
                        if (cba)
                        {
                            bool flag26 = string.IsNullOrEmpty(cBatch);
                            if (flag26)
                            {
                                row = 1;
                                res = string.Concat(new string[]
                                {
                                    res,
                                    "第[",
                                    (i + 1).ToString(),
                                    "]行存货[",
                                    cInvCode,
                                    "]进行批次管理,批次不允许为空,检查cBatch字段!"
                                });
                            }
                        }
                        if (!cba && !string.IsNullOrEmpty(cBatch))
                        {
                            row = 1;
                            res += "第[" + (i + 1) + "]行存货[" + cInvCode + "]未进行批次管理，不允许传批号!检查cBatch字段!";
                        }
                        string cWhCode = rd.Items[i].cWhCode;
                        if (string.IsNullOrEmpty(cWhCode))
                        {
                            row = 1;
                            res += "第[" + (i + 1) + "]行仓库编码不允许为空,请检查cWhCode字段!";
                        }
                        else
                        {
                            int ifex4 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
                            {
                                "select COUNT(*) from ",
                                AddRD01.DBname,
                                "..Warehouse where cWhCode='",
                                cWhCode,
                                "'"
                            })));
                            if (ifex4 == 0)
                            {
                                row = 1;
                                res = res + "仓库编码[" + cWhCode + "]在U8系统不存在!";
                            }
                        }
                        string dMadeDate = rd.Items[i].dMadeDate;
                        string cPosCode = rd.Items[i].cPosCode;
                        if (row == 0)
                        {
                            irow++;
                            cidas++;
                            list.Add(" update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='as' ");
                            string autoidas = "1" + string.Format("{0:D9}", cidas);
                            string cbsysbarcode = "||st15|" + dCode + "|" + (i + 1).ToString();
                            string avdSql = "insert into " + DBname + "..AssemVouchs " +
                                "(autoid,ID,cAVCode,bAVType,cWhCode,cInvCode,iAVQuantity,irowno,igroupno,cbsysbarcode) " +
                                "values ('" + autoidas + "','" + ASID + "','" + ASCode + "','" + bAVType + "','" + cWhCode + "','" + cInvCode + "','" + iQuantity + "'" +
                                ",'" + (i + 1) + "','1','" + cbsysbarcode + "')";
                            list.Add(avdSql);
                            rd.Items[i].Autoid = autoidas;
                            mir.Autoid = "";
                            mir.U8RowNo = (i + 1).ToString();
                            mir.U8ID = autoidas;
                            lim.Add(mir);
                        }
                    }
                    string cinvcode = "";
                    string qty = "0";
                    string iNum = "";
                    string iRate = "";
                    string AssUnit = "";
                    //货位
                    string cPosition = "null";
                    //批号  批次属性
                    string cbatch = "null";
                    //保质期
                    string dPDate = "null", dVDate = "null", cExpirationdate = "null", imassdate = "null", cmassunit = "null";

                    int fidrd = 0, cidrd = 0;
                    List<ItemsItem> items = rd.Items;
                    #region 其他出库单
                    Dictionary<string, List<ItemsItem>> map = items.GroupBy(e => e.bAVType).ToDictionary(e => e.Key, e => e.ToList());
                    Dictionary<string, List<ItemsItem>> beforeMap = map["转换前"].GroupBy(e => e.cWhCode).ToDictionary(e => e.Key, e => e.ToList());
                    foreach (string key in beforeMap.Keys)
                    {
                        #region 其他出库单 id,单号流水
                        sql = " select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ";
                        DataTable dtidrd = DBHelp.SQLHelper.GetDataTable(sql);
                        if (dtidrd.Rows.Count > 0)
                        {
                            fidrd = Convert.ToInt32(dtidrd.Rows[0]["iFatherId"].ToString());
                            cidrd = Convert.ToInt32(dtidrd.Rows[0]["iChildId"].ToString());
                        }
                        else
                        {
                            sql = " insert into UFSystem..UA_Identity (cAcc_Id,cVouchType,iFatherId,iChildId) " +
                                " values('" + cAcc_Id + "','rd',0,0) ";
                            DBHelp.SQLHelper.ExecuteSql(sql);
                        }
                        //// 单号
                        //sql = " select cNumber from VoucherHistory where CardNumber ='0302' and cSeed = '" + cSeed + "' ";
                        //DataTable dthis09 = U8SqlDBHelper.GetDataTable(sql);
                        //if (dthis09.Rows.Count > 0)
                        //    cNumber09 = Convert.ToInt32(dthis09.Rows[0]["cNumber"].ToString());
                        //else
                        //{
                        //    U8SqlDBHelper.GetExecute("insert into VoucherHistory (CardNumber,iRdFlagSeed,cContent,cContentRule,cSeed,cNumber,bEmpty)" +
                        //         " values ('0302',null,'日期','月','" + cSeed + "',0,0) ");
                        //}
                        #endregion


                        #region 其他出库单主表
                        //流水更新
                        fidrd++;
                        list.Add(" update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
                        string ID09 = "1" + string.Format("{0:D9}", fidrd);
                        //list.Add("update VoucherHistory set cNumber=cNumber+1 where CardNumber ='0302' and cSeed = '" + cSeed + "'");
                        //string Code09 = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') +
                        //    DateTime.Now.Day.ToString().PadLeft(2, '0') + cNumber09.ToString().PadLeft(4, '0');

                        string Code09 = "QTCK" + dCode;
                        string rd9csysbarcode = "||st09|" + Code09;
                        sql = " insert into rdrecord09(id,brdflag,cvouchtype,cbustype,csource, " +
                            " cwhcode,ddate,ccode,crdcode,chandler,cbuscode,cDepCode, " +
                            " cmaker,bpufirst,biafirst,vt_id,bisstqc,ibg_overflag,cbg_auditor,cbg_audittime,controlresult, " +
                            " iswfcontrolled,dnmaketime,dnmodifytime,dVeriDate,dnverifytime,iprintcount,cMemo,ctransflag,csysbarcode)  " +
                            " values (" + ID09 + ",N'0',N'09',N'转换出库',N'形态转换', " +
                            " '" + key + "','" + dDate + "','" + Code09 + "','"+cordcode+"','" + cHandler + "','" + dCode + "',NULL, " +
                            " N'" + cMaker + "',0,0,85,0,0,N'',N'',-1, " +
                            " 0,getdate(),Null,'" + dDate + "',getdate(),0,'" + cMemo + "','" + cTransFlag.ToString() + "','" + rd9csysbarcode + "') ";
                        list.Add(sql);
                        #endregion
                        int rd09irow = 0;
                        //其他出库子表对象
                        List<ItemsItem> avdsCK = beforeMap[key];
                        for (int i = 0; i < avdsCK.Count; i++)
                        {

                            #region 子表属性处理
                            cinvcode = avdsCK[i].cInvCode;
                            qty = avdsCK[i].iQuantity;
                            iNum = "";
                             iRate = "";
                             AssUnit = "";
                            //string AssQty = BasicDAL.GetAssQty(zt, cinvcode, qty, out iNum, out iRate, out AssUnit);
                            //货位
                             cPosition = "null";
                            string cWhCode = avdsCK[i].cWhCode;
                            if (bWhPos(DBname, cWhCode))
                                cPosition = "'" + avdsCK[i].cPosCode + "'";
                            //批号  批次属性
                             cbatch = "null";
                            if (IsBatch(DBname, cinvcode))
                                cbatch = "'" + avdsCK[i].cBatch + "'";

                            string sqlunit = string.Concat(new string[]
                            {
                                "select  cSTComUnitCode,isnull(iChangRate,NULL) iChangRate   from ",
                                AddRD01.DBname,
                                "..inventory i  left join ",
                                AddRD01.DBname,
                                "..ComputationUnit c  on i.cSTComUnitCode=c.cComunitCode  where cinvcode='",
                                cinvcode,
                                "'"
                            });
                            LogException.WriteiLog(filename, "采购入库辅计量单位编码查询语句：" + sqlunit, LogException.ilog, false);
                            DataTable dtiv = SQLHelper.GetDataTable(sqlunit);
                            bool flag28 = dtiv.Rows.Count > 0;
                            string cAssUnit;
                            string iinvexchrate;
                            if (flag28)
                            {
                                cAssUnit = "'" + dtiv.Rows[0]["cSTComUnitCode"].ToString() + "'";
                                bool flag29 = !string.IsNullOrEmpty(dtiv.Rows[0]["iChangRate"].ToString());
                                if (flag29)
                                {
                                    iinvexchrate = (dtiv.Rows[0]["iChangRate"].ToString() ?? "");
                                }
                                else
                                {
                                    iinvexchrate = "NULL";
                                }
                            }
                            else
                            {
                                cAssUnit = "NULL";
                                iinvexchrate = "NULL";
                            }

                            #endregion
                            #region 其他出库单子表
                            cidrd++;
                            list.Add("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
                            string autoid09 = "1" + string.Format("{0:D9}", cidrd);
                            rd09irow++;
                            sql = " Insert Into "+DBname+"..rdrecords09(autoid, id, cinvcode, inum, iquantity, cbatch, " +
                                "  bcosting, isotype, irowno,iinvexchrate,cassunit,iTrIds,cbMemo, " +
                                " cPosition,dMadeDate,dVDate,cExpirationdate,iMassDate,cMassUnit ) " +

                                " values(" + autoid09 + ", " + ID09 + ", '" + avdsCK[i].cInvCode + "', null, " + avdsCK[i].iQuantity + "," + cbatch + ", " +
                                " 1, 0, " + rd09irow + ", null, null,"+ avdsCK[i].Autoid+ ",null, " +
                                " " + cPosition + ",NULL,NULL,NULL,NULL,NULL  )";
                            list.Add(sql);

                            sql = " Insert Into " + DBname + "..Rdrecords09sub(autoid,id,cbg_itemcode,cbg_itemname,cbg_caliberkey1,cbg_caliberkeyname1,cbg_caliberkey2,cbg_caliberkeyname2, " +
                                " cbg_caliberkey3,cbg_caliberkeyname3,cbg_calibercode1,cbg_calibername1,cbg_calibercode2,cbg_calibername2,cbg_calibercode3,cbg_calibername3, " +
                                " ibg_ctrl,cbg_auditopinion,ibgstsum,ibgiasum,cbg_caliberkey4,cbg_caliberkeyname4,cbg_caliberkey5,cbg_caliberkeyname5,cbg_caliberkey6, " +
                                " cbg_caliberkeyname6,cbg_calibercode4,cbg_calibername4,cbg_calibercode5,cbg_calibername5,cbg_calibercode6,cbg_calibername6) " +
                                " values(" + autoid09 + ", " + ID09 + ", Null, Null, Null, Null, Null, Null, Null, Null, Null, Null, Null, Null, Null, Null, 0, Null, 0, Null, Null, Null, Null, " +
                                " Null, Null, Null, Null, Null, Null, Null, Null, Null)  ";
                            list.Add(sql);

                            //新增记账表
                            list.Add(@"insert into " + DBname + "..IA_ST_UnAccountVouch09(IDUN,IDSUN,cVouTypeUN,cBustypeUN)" +
                                                        " values ('" + ID09 + "','" + autoid09 + "','09','其他出库')");


                            #region----货位
                            //货位
                            if (bWhPos(DBname, cWhCode))
                            {
                                string wherebatch = " and isnull(cbatch,'') = '' ";
                                if (IsBatch(DBname, cinvcode))
                                    wherebatch = " and cbatch = '" + avdsCK[i].cBatch + "' ";
                                //货位记录
                                sql = " insert into " + DBname + "..InvPosition ( " +
                                " RdsID,RdID,cWhCode,cPosCode,cInvCode,cBatch, " +
                                " iQuantity,cHandler,dDate,bRdFlag,iTrackId, " +
                                " iMassDate,cMassUnit,iExpiratDateCalcu,cvouchtype,dVouchDate, " +
                                " dMadeDate,dVDate,cExpirationdate ) " +

                                " select autoid,id,'" + avdsCK[i].cWhCode + "','" + avdsCK[i].cPosCode + "',cinvcode,cbatch, " +
                                " " + qty + ",'','" + dDate + "',0,0, " +
                                " iMassDate,cMassUnit,iExpiratDateCalcu,'09','" + dDate + "', " +
                                " dMadeDate,dVDate,cExpirationdate " +
                                " from rdrecords09 where  autoid = '" + autoid09 + "' ";
                                list.Add(sql);

                                sql = "  update " + DBname + "..invpositionsum set iquantity = iquantity - " + qty + "  " +
                                    " where cwhcode = '" + avdsCK[i].cWhCode + "' and cposcode = '" + avdsCK[i].cPosCode + "' and cinvcode = '" + cinvcode + "' " + wherebatch;
                                list.Add(sql);
                            }
                            #endregion

                            #endregion
                        }
                    }
                    #endregion

                    #region --其他入库单
                    List<ItemsItem> afterOne = map["转换后"];
                    ItemsItem rk = afterOne[0];
                    fidrd++;
                    list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
                    string ID08 = "1" + string.Format("{0:D9}", fidrd);
                    //cNumber08++;
                    //U8SqlDBHelper.ExecuteSql("update VoucherHistory set cNumber=cNumber+1 where CardNumber ='0301' and cSeed = '" + cSeed + "' ");
                    //string Code08 = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') +
                    //    DateTime.Now.Day.ToString().PadLeft(2, '0') + cNumber08.ToString().PadLeft(4, '0');
                    string Code08 = "QTRK" + dCode;
                    string rd8csysbarcode = "||st08|" + Code08;
                    sql = " insert into " + DBname + "..rdrecord08(id,brdflag,cvouchtype,cbustype,csource," +
                        " cwhcode,ddate,ccode,crdcode,cbuscode,cDepCode, " +
                        " cmaker,bpufirst,biafirst,vt_id,bisstqc,bislsquery,iswfcontrolled,dnmaketime,dnmodifytime," +
                        " cHandler,dVeriDate,dnverifytime,iprintcount,cMemo,ctransflag,csysbarcode) " +
                        " values('" + ID08 + "', N'1', N'08', N'转换入库', N'形态转换', " +
                        " '" + rk.cWhCode + "', '" + dDate + "', '" + Code08 + "','"+cirdcode+"','" + dCode + "', NULL, " +
                        " '" + cMaker + "', 0, 0, 67, 0, 0, 0, getdate(), Null," +
                        " '" + cHandler + "','" + dDate + "', getdate(), 0,'" + cMemo + "','" + cTransFlag.ToString() + "','" + rd8csysbarcode + "') ";
                    list.Add(sql);
                    #region 子表属性处理
                    string cinvcodes = rk.cInvCode;
                    qty = rk.iQuantity;
                    iNum = "";
                    iRate = "";
                    AssUnit = "";
                    
                    //货位
                    cPosition = "null";
                    if (bWhPos(DBname,rk.cWhCode))
                        cPosition = "'" + rk.cPosCode + "'";


                    //批号  批次属性
                    cbatch = "null";
                    if (IsBatch(DBname,cinvcode))
                        cbatch = "'" + rk.cBatch + "'";

                    //保质期
                    dPDate = "null"; dVDate = "null"; cExpirationdate = "null"; imassdate = "null"; cmassunit = "null";
                    //if (IsInvQuality(cinvcode))
                    //{
                    //    dPDate = "'" + rk.dMadeDate + "'";
                    //    DateTime vdate = BasicDAL.GetVDate(cinvcode, rk.dMadeDate);
                    //    dVDate = "'" + vdate.ToString("yyyy-MM-dd") + "'";
                    //    cExpirationdate = "'" + vdate.AddDays(-1).ToString("yyyy-MM-dd") + "'";
                    //    imassdate = BasicDAL.GetMassdate(cinvcode);
                    //    cmassunit = BasicDAL.GetMassUnit(cinvcode);
                    //}
                    #endregion
                    #region --其他入库子表
                    cidrd++;
                    list.Add(" update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
                    string autoid08 = "1" + string.Format("{0:D9}", cidrd);

                    sql = " Insert Into " + DBname + "..rdrecords08(autoid,id,cinvcode,inum,iquantity,cbatch, " +
                        " bcosting,iexpiratdatecalcu,isotype,irowno,iinvexchrate,cassunit,iTrIds,cbMemo, " +
                        " cPosition,dMadeDate,dVDate,cExpirationdate,iMassDate,cMassUnit ) " +
                        " values('" + autoid08 + "', '" + ID08 + "', '" + rk.cInvCode + "', null, " + rk.iQuantity + "," + cbatch + ",  " +
                        "  1, 0,  0, " + irow + ", null, " + PublicMet.setvalue(2,AssUnit) + ","+rk.Autoid+",NULL, " +
                        " " + cPosition + "," + dPDate + "," + dVDate + "," + cExpirationdate + "," + imassdate + "," + cmassunit + " )";
                    list.Add(sql);

                    //未记账表s
                    sql = " insert " + DBname + "..IA_ST_UnAccountVouch08(IDUN, IDSUN, cVouTypeUN, cBustypeUN) " +
                        " values ('" + ID08 + "','" + autoid08 + "','08','其他入库') ";
                    list.Add(sql);

                    #region----货位
                    if (bWhPos(DBname, rk.cWhCode))
                    {
                        string wherebatch = " and isnull(cbatch,'') = '' ";
                        if (IsBatch(DBname, cinvcode))
                            wherebatch = " and cbatch = '" + rk.cBatch + "' ";

                        //货位记录
                        sql = " insert into " + DBname + "..InvPosition ( " +
                        " RdsID,RdID,cWhCode,cPosCode,cInvCode,cBatch, " +
                        " iQuantity,cHandler,dDate,bRdFlag,iTrackId, " +
                        " iMassDate,cMassUnit,iExpiratDateCalcu,cvouchtype,dVouchDate, " +
                        " dMadeDate,dVDate,cExpirationdate ) " +

                        " select autoid,id,'" + rk.cWhCode + "','" + rk.cPosCode + "',cinvcode,cbatch,  " +
                        " " + qty + ",'','" + dDate + "',1,0, " +
                        " iMassDate,cMassUnit,iExpiratDateCalcu,'08','" + dDate + "', " +
                        " dMadeDate,dVDate,cExpirationdate " +
                        " from rdrecords08 where autoid = '" + autoid08 + "' ";
                        list.Add(sql);

                        //
                        sql = " select 1 from " + DBname + "..invpositionsum (nolock) " +
                            " where cwhcode = '" + rk.cWhCode + "' and cposcode = '" + rk.cPosCode + "' and cinvcode = '" + cinvcode + "' " + wherebatch;
                        DataTable dtips = DBHelp.SQLHelper.GetDataTable(sql);
                        if (dtips.Rows.Count == 0)
                        {
                            sql = "  insert into " + DBname + "..invpositionsum (cWhCode,cPosCode,cInvCode,iQuantity,cBatch, " +
                                " iTrackid,dMadeDate,dVDate,cExpirationdate,cMassUnit,iMassDate) " +
                                " values ( '" + rk.cWhCode + "','" + rk.cPosCode + "','" + cinvcode + "', 0 ," + cbatch + ", " +
                                " 0," + dPDate + "," + dVDate + "," + cExpirationdate + "," + cmassunit + "," + imassdate + " )";
                            //sqllist.Add(sql); //先插入一条为0的现存量数据，再做更新数量的操作
                            DBHelp.SQLHelper.ExecuteSql(sql);
                        }
                        sql = "  update " + DBname + "..invpositionsum set iquantity = iquantity + " + qty + "  " +
                            " where cwhcode = '" + rk.cWhCode + "' and cposcode = '" + rk.cPosCode + "' and cinvcode = '" + cinvcode + "' " + wherebatch;
                        list.Add(sql);
                    }
                    #endregion
                    #endregion
                    #endregion

                    bool flag30 = row == 0;
                    if (flag30)
                    {
                        int count = SQLHelper.ExecuteSqlTran(list);
                        bool flag31 = count > 0;
                        if (flag31)
                        {
                            res += "转换成功";
                            mr.U8Code = dCode;
                            mr.Items = lim;
                            LogException.WriteiLog(filename, "转换成功[" + dCode + "]", LogException.ilog, false);
                        }
                        else
                        {
                            row = 1;
                            res += "转换单失败";
                        }
                    }
                }
                catch (Exception ex)
                {
                    row = 1;
                    LogException.WriteiLog(filename, "转换单异常:" + ex.Message, LogException.ilog, true);
                    res = res + "失败:" + ex.Message;
                }
            }
            else
            {
                row = 1;
                res += "未传任何数据!";
            }
            bool flag32 = row == 1;
            if (flag32)
            {
                mr.Code = "500";
                mr.Msg = res;
            }
            else
            {
                mr.Code = "200";
                mr.Msg = res;
            }
            return JsonConvert.SerializeObject(mr);
        }

        public static bool bWhPos(string dbname, string cwhcode)
        {
            bool res = false;
            if (DBHelp.SQLHelper.GetDataTable("select * from " + dbname + "..warehouse where cWhCode='" + cwhcode + "' and ISNULL(bWhPos,0)=1").Rows.Count > 0)
            {
                res = true;
            }
            return res;
        }
        public static bool IsBatch(string dbname, string cinvcode)
        {
            bool res = false;
            if (DBHelp.SQLHelper.GetDataTable("select * from " + dbname + "..inventory where cinvcode='" + cinvcode + "' and ISNULL(bInvBatch,0)=1").Rows.Count > 0)
            {
                res = true;
            }
            return res;
        }
    }
}